package com.example.constraintlayoutstudy.util;

import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import com.example.constraintlayoutstudy.R;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class ActivityCreateTimeAop {

  //是否允许快速点击
  private boolean isFastClick = false;
  private static final int MIN_CLICK_DELAY_TIME = 500;
  private static int TIME_TAG = R.id.button;

  @Around("execution(* android.app.Activity.setContentView(..))")
  public void onCreateTime(ProceedingJoinPoint joinPoint) {
    long start = System.currentTimeMillis();
    try {
      joinPoint.proceed();
    } catch (Throwable throwable) {
      throwable.printStackTrace();
    }
    Log.i("APO+"+joinPoint.getSignature().toString(),
        joinPoint.getSignature().toString() + " onCreate 执行时间>>>" + (System.currentTimeMillis()
            - start));
  }

  @Before("execution(* android.app.Activity.on**(..))")
  public void onActivityMethodBefore(JoinPoint joinPoint) throws Throwable {
    String key = joinPoint.getSignature().toString();
    Object[] args = joinPoint.getArgs();
    //Log.i("APO+"+joinPoint.getSignature().toString(), "onActivityMethodBefore: key=" + key + (args != null ? ("参数" + args.length + "个") : "无参数"));
  }

  @Around("call(* com.tanbo.rocery_store.APPAplication.**(..))")
  public void getTime(ProceedingJoinPoint joinPoint) {
    long start = System.currentTimeMillis();
    try {
      joinPoint.proceed();
    } catch (Throwable throwable) {
      throwable.printStackTrace();
    }
    Log.i("APO",
        joinPoint.getSignature().toString() + " onCreate 执行时间>>>" + (System.currentTimeMillis()
            - start));
  }

  @Around("execution(* android.view.View.OnClickListener.onClick(..))")
  public void aroundClick(ProceedingJoinPoint joinPoint) throws Throwable{
    //判断是否需要快速点击
    if(isFastClick){
      Log.i("APO+拦截点击","快速点击");
      joinPoint.proceed();
      isFastClick = false;
      return;
    }

    View view=null;
    for (Object arg: joinPoint.getArgs()) {
      if (arg instanceof View) {
        view= ((View) arg);
        break;
      }
    }
    if (view!=null){
      Object tag=view.getTag(TIME_TAG);
      long lastClickTime= (tag!=null)? (long) tag :0;
      long currentTime = SystemClock.uptimeMillis();
      if (currentTime - lastClickTime > MIN_CLICK_DELAY_TIME) {//过滤掉600毫秒内的连续点击
        view.setTag(TIME_TAG, currentTime);
        Log.i("APO+拦截点击","慢速点击");
        joinPoint.proceed();//执行原方法
      }else{
        Log.i("APO+拦截点击","过滤点击");
      }
    }
  }

}
